package com.naodong.shenluntiku.intergation.jobqueue;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.apkfuns.logutils.LogUtils;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.blankj.utilcode.util.FileUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.compress.Luban;
import com.naodong.shenluntiku.app.BootstrapApplication;
import com.naodong.shenluntiku.intergation.aliyunoss.OssManager;
import com.naodong.shenluntiku.intergation.aliyunoss.OssObject;
import com.naodong.shenluntiku.mvp.model.data.api.CommonApi;
import com.naodong.shenluntiku.mvp.model.error.ResponseErrorListener;
import com.naodong.shenluntiku.mvp.model.error.ResultHandleSubscriber;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import me.shingohu.man.intergation.retrofit.NoBodyEntity;


/**
 * Created by grey on 2017/6/15.
 */

public class FeedbackJob extends Job {

    private static final String TAG = "FeedbackJob";
    private int currentLink;
    private List<String> images;
    private List<File> reduceFiles;//压缩后图片文件
    private List<String> pathList;//上传的地址
    private String con;
    private String contact;
    private boolean isReduceComplete = false;//是否压缩完成
    private boolean isUploadComplete = false;//是否上传完成

    public FeedbackJob(String con, String contact, List<String> images) {
        super(new Params(Priority.LOW).requireNetwork().persist());
        this.images = images;
        this.con = con;
        this.contact = contact;
        currentLink = 0;
        reduceFiles = new ArrayList<>();
        pathList = new ArrayList<>();
    }

    @Override
    public void onAdded() {

    }


    @Override
    public void onRun() throws Throwable {
        if (currentLink == 3) {
            LogUtils.d(TAG, "onRun: The third failed to upload directly ");
            postFeedback();
            return;
        }
        if (!isReduceComplete) {
            List<File> files = new ArrayList<>();
            if (images.size() != 0) {
                Observable.fromArray(images.toArray(new String[images.size()]))
                        .map(s -> new File(s))
                        .filter(file -> FileUtils.isFileExists(file))
                        .subscribe(file -> files.add(file));
            }
            //压缩图片
            Luban.compress(getApplicationContext(), files)
                    .putGear(Luban.FIRST_GEAR)
                    .asListObservable()
                    .subscribeOn(Schedulers.computation())
                    .subscribe(files1 -> {
                        reduceFiles.clear();
                        reduceFiles.addAll(files1);
                        isReduceComplete = true;//标志压缩成功
                        pathList.clear();//重新上传，需清空
                        uploadImage();
                        postFeedback();
                    });
        } else {
            uploadImage();
            postFeedback();
        }
    }

    /**
     * 上传图片
     */
    private void uploadImage() throws ClientException, ServiceException {
        if (isUploadComplete)
            return;
        while (reduceFiles.size() > 0) {
            LogUtils.d( "File path is " + reduceFiles.get(0).getPath());
            String objectKey = OssObject.createImageOssObjectKeyByFile(reduceFiles.get(0).getPath());
            String uploadKey = OssManager.putImage(objectKey, reduceFiles.get(0).getPath());//同步上传
            if (objectKey.equals(uploadKey)) {
                reduceFiles.remove(0);
                pathList.add(uploadKey);
            }
        }
        isUploadComplete = true;
    }

    private void postFeedback() {


        BootstrapApplication.getInstance()
                .getAppComponent()
                .repositoryManager()
                .obtainRetrofitService(CommonApi.class)
                .feedback(con, contact, new Gson().toJson(pathList))
                .subscribeWith(new ResultHandleSubscriber<NoBodyEntity>(ResponseErrorListener.EMPTY) {
                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull NoBodyEntity noBodyEntity) {
                        LogUtils.d("提交成功");
                    }
                });
    }

    @Override
    protected void onCancel(int cancelReason, @Nullable Throwable throwable) {

    }


    @Override
    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
        //如果重试了3次仍未成功，那么就直接上传反馈,第四次就直接放弃任务
        currentLink = runCount;
        if (runCount == 4)
            return RetryConstraint.CANCEL;
        //这样的返回将导致onRun方法的再次执行，重试,重试将导致代码再次进入onRun。同时，runCount自加1
        return RetryConstraint.RETRY;
    }
}
